#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int count = 100;
    pid_t fpid = fork(); // 生成子进程，子进程返回0，父进程返回子进程的pid
    int cnt = 10;
    int status;
    pid_t waited_pid;
    if (fpid < 0)
    {
        perror("fork failed:");
        return 1;
    }
    else
    {
        if (fpid == 0)
        {
            while (cnt--)
            {
                count = count * 3;
                printf("我是子进程,我的id是: %d,我的父进程id是: %d,count=%d\n", getpid(), getppid(), count);
                sleep(1);
            }
            exit(2); // 子进程退出
        }
        else
        {
            while (cnt--)
            {
                count = count + 3;
                printf("我是父进程,我的id是: %d,我的子进程id是: %d,我的父进程id是: %d,count=%d\n", getpid(), fpid, getppid(), count);
                sleep(1);
            }
            waited_pid = waitpid(-1, &status, 0);

            if (waited_pid == -1)
            {
                // waitpid() 失败
                perror("waitpid failed");
                exit(EXIT_FAILURE);
            }
            else
            {
                // 检查子进程的退出状态
                if (WIFEXITED(status))
                {
                    printf("Child process exited with status %d.\n", WEXITSTATUS(status));
                }
                else
                {
                    printf("Child process did not exit normally.\n");
                }
            }
        }
        return 0;
    }
}